<template>
  <el-row>
    <el-col :span="24">
      <div style="width: 100%;">
        <el-card class="box-card">
          <el-form :label-position="label='right'" :inline="true" :model="goodsQuery" label-width="80px">
            <div :span="24" style="background-color: white">
              <el-link @click="allCategory" style="margin-left: 2%">全部</el-link>
              <el-link style="margin-left: 2%" v-for="(item,index) in category" :key="item.id"
                       @click="categoryOne(item.id)">
                {{item.name}}
              </el-link>
            </div>
            <el-divider></el-divider>
            <el-form-item label="销量≥">
              <el-input v-model="goodsQuery.sales">
                <template slot="append">个</template>
              </el-input>
            </el-form-item>
            <el-form-item label="粉丝≥">
              <el-input v-model="goodsQuery.fansNum">
                <template slot="append">人</template>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="queryFrom">搜索</el-button>
              <el-button type="primary" @click="cleanFrom">清除</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <el-row style="align-content: center;display:block;">
          <!--https://img.alicdn.com/bao/uploaded/i3/2361130281/O1CN01Xi978Y1DwjuyacOoe_!!2361130281.jpg_300x300.jpg-->
          <el-col style="width: 299px;margin-top:5px;margin-bottom: 1px;margin-left: 20px" :span="5"
                  v-for="(item, index) in listData"
                  :key="item.id">
            <el-card
              :body-style="{ padding: '0px', margin: '0px '}"
              shadow="hover">
              <img lazy fit="cover" style="cursor: pointer;width: 299px; height: 299px"
                   :src="item.image"
                   @click="openShop(item.goodsUrl)"/>
              <div style="padding: 0 14px 0 14px">
                <el-row style="margin: 15px 0 15px 0">
                  <!--<el-col :span="12">

                  </el-col>-->
                  <el-col :span="24" align="left">
                    {{item.name | ellipsis}}
                  </el-col>
                </el-row>
                <el-row style="margin: 15px 0 15px 0">
                  <el-col :span="5" style="text-align: left;border: 1px solid;width:60px;color: red;text-align: center">
                    一口价
                  </el-col>
                  <el-col :span="17" align="right" style="font-weight: bold;color: red">￥{{item.price}}元</el-col>
                </el-row>
                <el-row class="price">
                  <!--<el-col :span="12" style="text-align: left;font-size: 13px;
        color: #999; ">自购价：￥{{item.minePrice}}
                  </el-col>-->
                  <el-col :span="12" align="left">佣金：<span class="span">{{item.commission}}%</span></el-col>
                </el-row>
                <el-row class="price">
                  <!--<el-col :span="12" style="text-align: left">销量：<span class="span">{{item.sales}}</span></el-col>-->
                  <el-col :span="12" style="text-align: left">要求粉丝：<span class="span">{{item.fansNum}}</span></el-col>
                </el-row>
                <el-row class="price">
                  <el-col :span="12" style="text-align: left">可领取数量:{{item.receiveNum}}</el-col>
                  <el-col :span="12" style="text-align: right">剩余数量:<span class="span">{{item.remainNum}}</span>
                  </el-col>
                </el-row>
                <el-row class="price">
                  <el-col style="text-align: left">活动时间：{{dateFormat(item.start)}} - {{dateFormat(item.end)}}
                  </el-col>
                </el-row>
                <el-row>
                  <el-col style="text-align: left">
                    <el-button class="bar_btn copy_btn " type="text" :data-clipboard-text="item.goodsUrl"
                               @click="handCopyLink()">复制商品链接
                    </el-button>
                  </el-col>
                </el-row>
                <el-row style="text-align: center;margin: 15px 0 15px 0">
                  <el-col>
                    <el-button size="mini" plain @click="handleFreeCollection(item)">免费领取</el-button>
                    <el-button size="mini" plain @click="handlePoint(item.characteristic)">商品卖点</el-button>
                  </el-col>
                </el-row>
              </div>
              <el-row style="background-color: #F2F2F2;color: #999999">
                <el-col align="center">
                  {{item.shopName}}
                </el-col>
              </el-row>
            </el-card>
          </el-col>
        </el-row>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>

        <el-dialog title="领取信息填写" :visible.sync="dialogFormVisible">
          <div style="text-align:left;font-weight: bold;font-size: 30px">{{goods.name}}</div>
          <div style="text-align:left">活动时间：<span
            class="span">{{dateFormat(goods.start)}} - {{dateFormat(goods.end)}}</span></div>
          <div>
            <el-row>
              <el-col :span="5" align="left">佣金：<span class="span">{{goods.commission}}%</span></el-col>
            </el-row>
          </div>
          <el-form :label-position="label='left'" :rules="formRules" ref="formRulesRef" :model="formData"
                   label-width="80px"
                   style="margin-top: 15px">
            <el-form-item label="收件人" prop="userName">
              <el-input v-model="formData.userName"></el-input>
            </el-form-item>
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="formData.phone"></el-input>
            </el-form-item>
            <el-form-item label="微信号" prop="wechat">
              <el-input v-model="formData.wechat"></el-input>
            </el-form-item>
            <el-form-item label="收件地址" prop="characteristic">
              <el-input v-model="formData.characteristic"></el-input>
            </el-form-item>
            <el-form-item label="推广方式" style="text-align: left" prop="model">
              <el-radio-group v-model="formData.model">
                <el-radio label="抖音短视频"></el-radio>
                <el-radio label="直播"></el-radio>
                <el-radio label="抖音短视频+直播"></el-radio>
              </el-radio-group>
            </el-form-item>
            <div style="color: red;text-align: left">选择您将会使用的推广方式,推广方式是商家审核考虑因素之一。</div>
            <div style="color: darkgray;margin-top: 9px;text-align: left">选择将用作发布视频的抖音号(选择精准的抖音号，会提高审核通过率)</div>
            <el-form-item label="选择账号" style="margin-top: 9px;text-align: left" prop="account">
              <el-checkbox-group v-model="formData.account" v-for="(item,index) in douyinInfoList"
                                 :key="item.id">
                <el-checkbox :label="item.nickname" name="type">{{item.nickname}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-input
              type="textarea"
              :rows="2"
              placeholder="输入备注内容，方便商家审核"
              v-model="formData.message"
              style="margin-top: 9px">
            </el-input>
          </el-form>
          <div slot="footer" align="center">
            <el-button type="primary" @click="handleOnSubmit(goods)">提交</el-button>
            <el-button @click="dialogFormVisible = false">取 消</el-button>
          </div>
        </el-dialog>

        <el-dialog
          title="打开微信扫一扫"
          :visible.sync="ticketDialog"
          width="25%"
          center>
          <el-image
            style="width: 100%;height: 100%;"
            :src="this.ticket"
            fit="cover"></el-image>
          <div style="color: #999;text-align: center;font-size: 20px">关注公众号</div>
          <div style="color: #999;text-align: center;font-size: 20px">追踪推广进度</div>
          <div style="color: #999;text-align: center;font-size: 20px">获取专属客服一对一支持</div>
        </el-dialog>
      </div>
    </el-col>
  </el-row>
</template>

<script>
  import {setToken, getToken} from '@/utils/cookie'
  import ElRow from "element-ui/packages/row/src/row";
  import ElCol from "element-ui/packages/col/src/col";
  export default {
    components: {
      ElCol,
      ElRow
    },
    filters: {
      ellipsis(value) {
        if (!value) return "";
        if (value.length > 5) {
          return value.substr(0, 13) + "...";
        }
        return value;
      }
    },
    data() {
      return {
        dialogFormVisible: false,
        copyLinkDialog: false,
        ticketDialog: false,
        userId: null,
        ticket: '',
        timer: '',
        currentPage: 0,
        total: 0,
        listData: [],
        category: [],
        formData: {
          account: []
        },
        goodsQuery: {
          categoryId: null,
          price: 9.9
        },
        goods: {}
        ,
        douyinInfoList: [],
        formRules: {
          userName: [
            {required: true, message: '请输入收件人', trigger: 'blur'}
          ],
          phone: [
            {required: true, message: '请输入联系电话', trigger: 'blur'},
            {
              pattern: /^1[3456789]\d{9}$/,
              message: '请输入正确的手机号'
            }
          ],
          characteristic: [
            {required: true, message: '请输入收件地址', trigger: 'blur'}
          ],
          model: [
            {required: true, message: '请选择推广方式', trigger: 'blur'}
          ],
          account: [
            {required: true, message: '请选择账号', trigger: 'blur'}
          ],
          wechat: [
            {required: true, message: '请输入微信号', trigger: 'blur'}
          ],
        },
        result_img: '',
        final_img: ''
      };
    },
    created(){
      this.getGoodsList();
      this.getCategory();
    },
    /*  mounted() {
     this.timer = setInterval(this.getUser, 1000);
     },*/
    /* beforeDestroy() {
     clearInterval(this.timer);
     },*/
    methods: {
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.getGoodsList()
        console.log(`当前页: ${val}`);
      },
      getUser(val){
        this.$http.defaults.headers.common['Authorization'] = 'Bearer ' + getToken()
        this.$http.get(`/weixin/getUserId`).then((res) => {
          this.$http.get(`/wx/user/${res.data.data}`).then((res) => {
            console.log('1', res)
            if (res.data.data === 0) {
//              this.timer = setTimeout(this.getUser(val), 3000);
              this.time = setTimeout(this.getUser, 3000);
            } else {
              clearTimeout(this.timer);
              this.ticketDialog = false;
              this.onSubmit(val);
            }
          })
        })
      },
      handleOnSubmit(val){
        clearTimeout(this.timer);
        this.$refs.formRulesRef.validate(valid => {
          if (!valid) {
            this.$message.error('请安要求填写数据')
          } else {
            //判断用户信息中存在openId
            this.$http.defaults.headers.common['Authorization'] = 'Bearer ' + getToken()
            this.$http.get(`/weixin/getUserId`).then((res) => {
              this.$http.get(`/wx/user/${res.data.data}`).then((res) => {
                console.log('2', res)
                if (res.data.data === 0) {
                  //如何存在 直接领取提交信息
                  //如果不存在需先扫码 在提交信息
                  this.ticketDialog = true;
                  this.handleTicket();
                  this.getUser(val);
                } else {
                  this.onSubmit(val);
                }
              })
            })
          }
        })
      },
      onSubmit(val){
        this.formData.goodsId = val.id
        this.formData.accountNameList = this.formData.account
        this.formData.shopName = val.shopName
        this.formData.goodsUrl = val.goodsUrl
        this.$http.defaults.headers.common['Authorization'] = 'Bearer ' + getToken()
        this.$http.post('/order/save', this.formData).then((res) => {
          if (res.data.code === 200) {
            this.$message.success("添加成功")
            this.dialogFormVisible = false
          } else {
            this.$message.success(res.data.msg)
          }
        })
      },
      getCategory(){
        this.$http.defaults.headers.common['Authorization'] = ''
        this.$http.get(`/goods/category/list`).then((res) => {
          console.log(res)
          this.category = res.data.data
        })
      },
      openShop(val){
        window.location.href = val
      },
      handlePoint(val){
        this.$alert(val, '商品卖点', {
          confirmButtonText: '确定',
        });
      },
      handleFreeCollection(val){
        const token = getToken()
        if (token) {
          this.dialogFormVisible = true
          this.goods = val
          console.log(this.goods)
          this.getDouyinUserInfoList();
        } else {
          this.$message.warning("需要登录")
        }
      },
      getGoodsList(){
        this.$http.defaults.headers.common['Authorization'] = ''
        this.$http.post(`/goods/list/${this.currentPage}`, this.goodsQuery).then((res) => {
          this.total = res.data.data.total
          this.listData = res.data.data.list
        })
      },
      allCategory(){
        this.goodsQuery.categoryId = null
        this.getGoodsList();
      },
      categoryOne(val){
        this.goodsQuery.categoryId = val
        this.getGoodsList();
      },
      queryFrom(){
        console.log(this.goodsQuery.sales)
        console.log(this.goodsQuery.categoryId)
        this.getGoodsList();
      },
      cleanFrom(){
        this.goodsQuery = {}
        this.getGoodsList();
      },
      getDouyinUserInfoList(){
        this.$http.defaults.headers.common['Authorization'] = 'Bearer ' + getToken()
        this.$http.get('/base/douyin/bind/info/list').then((res) => {
          console.log(res)
          this.douyinInfoList = res.data.data
        })
      },
      dateFormat: function (time) {
        var date = new Date(time);
        var year = date.getFullYear();
        /* 在日期格式中，月份是从0开始的，因此要加0
         * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
         * */
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
        var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
        var seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
        // 拼接
        return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
      },
      handCopyLink(){
        var clipboard = new this.clipboard('.copy_btn')
        clipboard.on('success', e => {
          this.showMessage('已成功复制商品链接', 'success')
          clipboard.destroy()
        })

        clipboard.on('error', e => {
          this.showMessage('该浏览器不支持自动复制', 'error');
          clipboard.destroy()
        })
      },
      showMessage(message, type) {
        switch (type) {
          case 'success':
            this.$message.success(message)
            break;
          case 'error':
            this.$message.error(message)
        }
      },
      handleTicket(){
        this.$http.defaults.headers.common['Authorization'] = 'Bearer ' + getToken()
        this.$http.get(`/weixin/getUserId`).then((res) => {
          this.$http.post(`/weixin/getTicket/${ res.data.data + ''}`).then((res) => {
            const result = res.data
            this.ticket = result.data.ticket
          })
        })
      }
    }
  }
</script>

<style>
  .price {
    font-size: 13px;
    color: #999;
    margin: 15px 0 15px 0
  }

  .span {
    color: red;
  }
</style>
